package com.glaciervirtualdevice.quart;

import com.alibaba.fastjson.JSON;
import com.glaciervirtualdevice.dto.THDateDTO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @Author: Sun
 * @DateTime: 2025/4/1 16:00
 * @Description:随机生成一个温湿度任务
 **/
@Component
public class WarmHumidJob implements Job {

    private static final Random random = new Random();
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
//        System.out.println("job");
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        int baseTemperature = jobDataMap.getInt("warmDate");
        int baseHumidity = jobDataMap.getInt("humidDate");

        int temperature = random.nextInt(11) + baseTemperature - 5;
        int humidity = random.nextInt(11) + baseHumidity - 5;
        THDateDTO result = new THDateDTO();
        result.setHum(humidity);
        result.setTem(temperature);


        String groupName = context.getJobDetail().getKey().getGroup();
        WarmHumidQuartz.storeGroupResult(groupName, result);
        System.err.println(result);

        // 获取组名作为 redis 的 key
        String sn = context.getJobDetail().getKey().getGroup();
        System.err.println(sn);

//         更新 redis 的温湿度
        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(sn);
        ops.put("hum", String.valueOf(humidity));
        ops.put("tem", String.valueOf(temperature));
        //发布消息
        String jsonResult = JSON.toJSONString(result);//把结果类转化为JSON发布出去
        redisTemplate.convertAndSend(sn,jsonResult);
    }
}